#!/usr/bin/env ruby
#
#  Created by sjavey on 2007-07-07.
#  Copyright (c) 2007. All rights reserved.

require 'rexml/document'
require 'n19gpx/trackpoint'

module N19GPX
  class Track
    attr_reader :name
    attr_reader :number
    attr_reader :points
    attr_reader :min_ele
    attr_reader :max_ele
    attr_reader :min_point
    attr_reader :max_point
  
    def initialize(trackElement)
      @name = trackElement.elements["name"].text
      num = trackElement.elements["number"]
      @number = num ? num.text : "0"  
      @points = Array.new()
      @min_ele = -1
      @max_ele = -1
      trackElement.elements.to_a("trkseg/trkpt").each {|t| 
        init_track(N19GPX::TrackPoint.new(t))
      }
    end

    def init_track(point)
      #puts "#{point.ele} : #{point.lat} : #{point.lon} : #{point.time}"
      @points << point
      @min_ele = point.ele if @min_ele == -1
      @max_ele = point.ele if @max_ele == -1
      @min_ele = point.ele if point.ele < @min_ele
      @max_ele = point.ele if point.ele > @max_ele
      min_ele_point(point)
      max_ele_point(point)
    end

    def min_ele_point(p)
      if (@min_point == nil) 
        @min_point = p
        return 
      end
      @min_point = p if (@min_point.ele > p.ele)
    end

    def max_ele_point(p)
      if (@max_point == nil) 
        @max_point = p
        return 
      end
      @max_point = p if (@max_point.ele < p.ele)
    end
    
    def javascript
      str = <<EOS
    
    function N19_Track(name, number, points) {
      this.name = name;
      this.number = number;
      this.points = points;
      this.overlay = null;
    }
EOS
    end
  end
end